package com.wry.im.handler.v2;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.wry.im.entity.ChatMessage;
import com.wry.im.entity.Result;
import com.wry.im.enums.MessageType;
import com.wry.im.server.ChatNettyServer;
import com.wry.im.utlis.R;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * <h1>  <h1>
 *
 * @author wry
 * @since 2023/4/28 10:31
 */
public class ChatHandler {

    public static void execute(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) {
        final ChatMessage chat = JSON.parseObject(textWebSocketFrame.text(), ChatMessage.class);

        switch (MessageType.getEnumByCode(chat.getType())){
            case PRIVATE:
                if (StrUtil.isNotBlank(chat.getTarget())) {
                    channelHandlerContext.channel().writeAndFlush(Result.fail("消息发送失败，消息发送前请指定接收对象"));
                    return;
                }
                Channel channel = ChatNettyServer.USERS.get(chat.getTarget());
                if (null == channel || !channel.isActive()) {
                    channelHandlerContext.channel().writeAndFlush(Result.fail("消息发送失败，对方" + chat.getTarget() + "不在线"));
                } else {
                    channel.writeAndFlush(Result.success("私聊消息(" + chat.getNickname() + ")", chat.getContent()));
                }
                break;
            case GROUP:
                ChatNettyServer.GROUP.writeAndFlush(Result.success("群聊消息(" + chat.getNickname() + ")", chat.getContent()));
                break;
            default:
                channelHandlerContext.channel().writeAndFlush(Result.fail("不支持消息类型"));
        }
    }
}
